#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
using namespace std;
static const string ip = "127.0.0.1";
static const uint16_t port = 8080;
bool flag = 0;
int main(int argc, char *argv[])
{
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    server.sin_port = htons(port);
    connect(socket_fd, (struct sockaddr *)&server, sizeof(server));
    int epoll_fd = epoll_create(1);
    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = STDIN_FILENO;
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, STDIN_FILENO, &event);
    struct epoll_event event_fd;
    event_fd.events = EPOLLIN;
    event_fd.data.fd = socket_fd;
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, socket_fd, &event_fd);
    while (true)
    {
        struct epoll_event array[10];
        memset(array, 0, sizeof(array));
        int num = epoll_wait(epoll_fd, array, 10, -1);
        for (int i = 0; i < num; i++)
        {
            if (array[i].data.fd == STDIN_FILENO)
            {
                char buffer[1024] = {0};
                int ret_read = read(STDIN_FILENO, buffer, sizeof(buffer));
                send(socket_fd, buffer, ret_read, 0);
            }
            if (array[i].data.fd == socket_fd)
            {
                char buffer[1024] = {0};
                int ret_recv = recv(socket_fd, buffer, sizeof(buffer), 0);
                buffer[ret_recv] = 0;
                if (ret_recv == 0)
                {
                    printf("服务器主动关闭了链接, 我也关闭并退出!\n");
                    flag = 1;
                    break;
                }
                printf("buf : %s\n", buffer);
            }
        }
        if (flag == 1)
        {
            break;
        }
    }
    close(socket_fd);
    return 0;
}